var ZYRequestClient = require("../../../../utils/zy-request");
var requestClient;
const app = getApp();
Page({
  data:{
    processId:0,
    processName:'',
    enableFlag:1,
    companyId:0,
    createUser:0,
    formData: {},
    rules: [
      {
          name: 'name',
          rules: {required: true, message: '请选择输入审批名称'},
      }
    ],

    sealList:[],
    showSealDialog:false,
    selectedSeal:null,
    approvalProcessData:null,

    showDepartmentDialog:false,
    departmentLevel:0,
    selectDepartmentIds:[],
    checkDepartmentId:0,
    checkDepartmentName:'无',
    departmentList:[],

    showUserDialog:false,
    selectUserTitle:'',
    selectUserIds:[],
    companyUserList:[],

    showUserType:0,
    selectLevel:0,
    approvalUserList:[{level:0,ids:[],names:'无'}],

    ccUser:{ids:[],names:'无'},
    navbarData:{
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '审批流程', //导航栏 中间的标题
      white:true
     },
     // 导航头的高度
     height: app.globalData.height * 2 + 20
  },
  onLoad(options) {
    requestClient = new ZYRequestClient();
    var defaultCompany = wx.getStorageSync('defaultCompany');
    var userInfo = wx.getStorageSync('userInfo');
    var _this = this;
    _this.setData({
      companyId:defaultCompany.id,
      createUser:userInfo.id
    });
    // 获取审批流id
    var processId = options.processId;
    // 获取可用状态
    var enableFlag = options.enableFlag;
    _this.setData({
      processId:parseInt(processId),
      enableFlag:parseInt(enableFlag)
    });
  },
  onShow(){
    var _this = this;
    // 判断是否为添加审批流
    if(_this.data.processId == 0 && _this.data.enableFlag){
      requestClient.checkFunctionPermission(2001,'您没有权限设置审批流，请联系企业创建者！',function(){},function(){
        wx.navigateBack({
          delta: 1,
        })
      });
    }
    // 加载审批流信息
    _this.loadApprovalProcess();
  },
  // 加载审批流信息
  loadApprovalProcess(){
    var _this = this;
    requestClient.getApprovalProcessDetail(_this.data.processId,function(res){
      if(res.data.data){
        _this.setData({
          approvalProcessData:res.data.data,
          processName:res.data.data.approvalProcess.name,
          'formData.name':res.data.data.approvalProcess.name,
          checkDepartmentId:res.data.data.approvalProcess.departmentId,
          checkDepartmentName:res.data.data.approvalProcess.departmentName,
          approvalUserList:res.data.data.approvalUserList,
          ccUser:res.data.data.ccUser
        });
      }
      // 加载公司印章列表
      _this.loadCompanySealList();
    });
  },
  // 选择印章
  bindShowSelectSeal(e){
    var _this = this;
    if(_this.data.enableFlag == 0){
      return;
    }
    // 判断如果是修改审批流则不能选择印章
    if(_this.data.processId != 0){
      return;
    }
    _this.setData({
      showSealDialog:true,
    });
  },
  bindSealCheck(e){
    var _this = this;
    _this.setData({
      showSealDialog:false,
    });
    var id = e.detail.value;
    if(!!id){
      var sealList = _this.data.sealList;
      for(var i=0;i<sealList.length;i++){
        if(sealList[i].id == parseInt(e.detail.value)){
          _this.setData({
            selectedSeal:sealList[i]
          });
          break;
        }
      }
    } else {
      _this.setData({
        selectedSeal:null,
      });
    }
  },
  bindClosedSeal(e){
    var _this = this;
    _this.setData({
      showSealDialog:false,
    });
  },
  // 加载公司印章列表
  loadCompanySealList(){
    var _this = this;
    requestClient.getSealList(_this.data.companyId,function(res){
      _this.setData({
        sealList:res.data.data
      });
      // 设置选中的印章
      for(var i = 0;i<res.data.data.length;i++){
        var seal = res.data.data[i];
        if(_this.data.approvalProcessData){
          if(seal.id == _this.data.approvalProcessData.approvalProcess.sealId){
            _this.setData({
              selectedSeal:seal,
            });
          }
        }
      }
    });
  },
  // 加载公司所有用户
  loadCompanyAllUserList(){
    var _this = this;
    requestClient.getAllUserList(_this.data.companyId,function(res){
        _this.setData({
          companyUserList:res.data.data
        });
    });
  },
  // 加载公司部门
  loadCompanyDepartmentList(){
    var _this = this;
    requestClient.getCompanyResource(_this.data.companyId,function(res){
       var allDepartment = {id:0,name:'公司全员'};
       var departmentList = res.data.data.departmentVoList;
       departmentList.splice(0,0,allDepartment);
      _this.setData({
        departmentList:departmentList
      });
    });
  },
  // 加载子部门
  loadDepartmentList(parentId){
    var _this = this;  
    requestClient.getDepartmentResource(parentId,function(res){
          _this.setData({
            departmentList:res.data.data.departmentVoList
          });
      });
  },
  // 输入审批流名称
  formInputChange(e) {
    const {field} = e.currentTarget.dataset;
    this.setData({
        [`formData.${field}`]: e.detail.value,
        processName:e.detail.value
    })
  },
  // 显示申请人选择框
  bindShowDepartment(e){
    if(this.data.enableFlag == 0){
      return;
    }
    var _this = this;
    _this.setData({
      showDepartmentDialog:true,
      // departmentLevel:0,
      // selectDepartmentIds:[_this.data.companyId],
      // checkDepartmentId:-1,
      // checkDepartmentName:'无'
    });
    _this.loadCompanyDepartmentList();
  },
  // 关闭选择部门
  bindClosedDepartment(e){
      // var _this = this;
      // _this.setData({
      //   checkDepartmentId:-1,
      //   checkDepartmentName:'无'
      // });
  },
  // 选中部门
  departmentCheckboxChange(e){
      var _this = this;
      _this.setData({
        checkDepartmentId:parseInt(e.detail.value)
      });
  },
  // 返回上级部门
  bindBackClick(e){
    var _this = this;
    _this.setData({
      checkDepartmentId:-1
    });
    var level = _this.data.departmentLevel;
    if(level <= 0){
        level = 0;
        _this.setData({
          departmentLevel:level
        });
       _this.loadCompanyDepartmentList();
       return;
    } 
    level--;
    _this.setData({
      departmentLevel:level
    });
    if(level == 0){
      _this.loadCompanyDepartmentList();
    } else {
      _this.loadDepartmentList(_this.data.selectDepartmentIds[level]);
    }
   
  },
  // 长按部门进入下一级
  bindDepartmentLongPress(e){
    var _this = this;
    var department = e.currentTarget.dataset.department;
    var level = _this.data.departmentLevel;
    level++;
    var departmentIds = _this.data.selectDepartmentIds;
    departmentIds.splice(level,0,department.id);
    _this.setData({
      departmentLevel:level,
      selectDepartmentIds:departmentIds,
      checkDepartmentId:-1
    });
    _this.loadDepartmentList(department.id);
  },
  // 确认选择部门
  bindDepartmentCheck(e){
    var _this = this;
    _this.setData({
      showDepartmentDialog:false
    });
    if(_this.data.checkDepartmentId != -1){
        for(var i=0;i<_this.data.departmentList.length;i++){
          var department = _this.data.departmentList[i];
          if(_this.data.checkDepartmentId == department.id){
            _this.setData({
              checkDepartmentName:department.name
            });
          }
        }
    }
  },
  // 添加审批层级
  bindAddApprovalClick(e){
    if(this.data.enableFlag == 0){
      return;
    }
    var level = e.currentTarget.dataset.level;
    var _this = this;
    var approvalUserList = _this.data.approvalUserList;
    approvalUserList.splice(level,0,{level:level,ids:[],names:'无'});
    _this.setData({
      approvalUserList:approvalUserList
    });
  },
  // 显示审批人选择框 
  bindShowApprovalUserList(e){
    if(this.data.enableFlag == 0){
      return;
    }
    var level = e.currentTarget.dataset.level;
    // var approvalUser = this.data.approvalUserList[level];
    // approvalUser.ids=[];
    // approvalUser.names='无';
    // var newApprovalUser = 'approvalUserList[' + level + ']';
    // this.setData({
    //   [newApprovalUser]:approvalUser
    // });
    this.setData({
        showUserDialog:true,
        showUserType:0,
        selectUserIds:[],
        selectUserTitle:'请选择审批人',
        selectLevel:level
      });
    this.loadCompanyAllUserList();
  },
  // 显示抄送人选择框
  bindShowCCList(e){
    if(this.data.enableFlag == 0){
      return;
    }
    this.setData({
      showUserDialog:true,
      showUserType:1,
      selectUserTitle:'请选择抄送人',
      selectUserIds:[]
    });
    this.loadCompanyAllUserList();
  },
  // 用户选中事件
  userCheckboxChange(e){
    this.setData({
      selectUserIds:e.detail.value
    });
  },
  // 确认选择用户
  bindUserCheck(e){
    var _this = this;
    _this.setData({
      showUserDialog:false
    });
    // 判断是否选择用户
    if(_this.data.selectUserIds.length == 0){
        return;
    }
    // 判断是否添加审批人
    if(_this.data.showUserType == 0){
       // 找到此层级的审批人
       var approvalUser = _this.data.approvalUserList[_this.data.selectLevel];
       // 赋值选中的用户id
       approvalUser.ids = _this.data.selectUserIds;
       // 赋值选中的用户名称
       var names = [];
       for(var i =0; i<approvalUser.ids.length;i++){
            var id = approvalUser.ids[i];
            for(var j = 0;j<_this.data.companyUserList.length;j++){
              var user=_this.data.companyUserList[j];
              if(user.id == parseInt(id)){
                names.push(user.nickName);
              }
            }
       }
       approvalUser.names = names.join(',');
       var newApprovalUser = 'approvalUserList[' + _this.data.selectLevel + ']';
       _this.setData({
          [newApprovalUser]:approvalUser
        });
        
    } else {
      // 添加抄送人
      var ccUser = {ids:_this.data.selectUserIds,names:''};
      // 赋值选中的用户名称
      var names = [];
      for(var i =0; i<ccUser.ids.length;i++){
           var id = ccUser.ids[i];
           for(var j = 0;j<_this.data.companyUserList.length;j++){
             var user=_this.data.companyUserList[j];
             if(user.id == parseInt(id)){
               names.push(user.nickName);
             }
           }
      }
      ccUser.names = names.join(',');
      _this.setData({
        ccUser:ccUser
      });
    }
  },
  // 关闭选择用户
  bindClosedUser(e){
    // this.setData({
    //   selectUserIds:[]
    // });
  },
  // 长按审批人显示删除次层级
  bindLongPressApprovalUser(e){
    if(this.data.enableFlag == 0){
      return;
    }
    var _this = this;
    var level = e.currentTarget.dataset.level;
    wx.showActionSheet({
      itemList: ['删除此层审批'],
      itemColor:'#ff0000',
      success(e){
        var approvalUserList = _this.data.approvalUserList;
        approvalUserList.splice(level,1);
        _this.setData({
          approvalUserList:approvalUserList
        });
      }
    })
  },
  // 长按清空抄送人 
  bindLongPressCCUser(){
    if(this.data.enableFlag == 0){
      return;
    }
    var _this = this;
    wx.showActionSheet({
      itemList: ['删除抄送人'],
      itemColor:'#ff0000',
      success(e){
        _this.setData({
          ccUser:{ids:[],names:'无'},
        });
      }
    })
  },
  // 保存提交
  bindSaveClick(e){
    let that = this;
    that.selectComponent('#form').validate((valid, errors) => {
      if (!valid) {
          const firstError = Object.keys(errors)
          if (firstError.length) {
            that.setData({
                  error: errors[firstError[0]].message
              })
          }
          wx.showToast({
            title: '请输入审批名称',
            icon:'none'
          })
      } else {
        // 判断是否选择印章
        if(that.data.selectedSeal == 0){
          wx.showToast({
            title: '请选择印章',
            icon:'none'
          })
          return;
        }
        // 判断是否选择部门
        // if(that.data.checkDepartmentId == -1){
        //   wx.showToast({
        //     title: '请选择部门',
        //     icon:'none'
        //   })
        //   return;
        // }
        // 重新构造审批人列表
        var approvalUsers = [];
        var levelIndex =0;
        for(var i=0;i<that.data.approvalUserList.length;i++){
          var approvalUser = that.data.approvalUserList[i];
          if(approvalUser.ids.length > 0){
            var newApprovalUser = {
              level:levelIndex,
              ids:approvalUser.ids
            };
            approvalUsers.push(newApprovalUser);
            levelIndex++;
          } else {
            continue;
          }
        }
        // 判断是否添加审批人
        if(approvalUsers.length == 0){
          wx.showToast({
            title: '请选择审批人',
            icon:'none'
          })
          return;
        }
        // 构造完整审批流数据
        var approvalProcessData = {
            approvalProcess:{
              id:that.data.processId,
              name:that.data.processName,
              sealId:that.data.selectedSeal.id,
              departmentId:that.data.checkDepartmentId,
              companyId:that.data.companyId,
              enableFlag:true,
              createUser:that.data.createUser
            },
            approvalUserList:approvalUsers,
            ccUserList:that.data.ccUser.ids
        }
        wx.showModal({
          title:'设置审批流',
          content:'您确定要设置此审批流吗?',
          success(e){
            if(e.confirm){
              requestClient.checkFunctionPermission(2001,'您没有权限设置审批流，请联系企业创建者！',function(){
                  // 提交
                  requestClient.setApprovalProcess(approvalProcessData,function(res){
                    if(res.data.data){
                      wx.showToast({
                        title: '审批流设置成功!',
                        icon:'success',
                        mask:true,
                      })
                      setTimeout(() => {
                        wx.navigateBack({
                          delta: 1,
                        })
                      }, 2000);
                    } else {
                      wx.showModal({
                        title:'设置失败',
                        content:'您已经在此印章设置了相同名称的审批流程，请重新填写审批名称',
                        showCancel:false,
                        success(r){
                        
                        }
                      })
                    }
                  });
              },function(){
                wx.navigateBack({
                  delta: 1,
                })
              });
            }
          }
        })
      }
    })
  }
})